package main

import (
	"fmt"
	"math"
	"path/filepath"

	"demserver/src/elevation"
)

func main() {
	// Use the actual GeoTIFF file
	filename := "./demdata/scdjy.tif"

	// Get absolute path to the file
	absPath, err := filepath.Abs(filename)
	if err != nil {
		fmt.Printf("Failed to get absolute path: %v\n", err)
		return
	}

	fmt.Printf("Loading GeoTIFF file: %s\n", absPath)
	geoTiff, err := elevation.LoadGeoTIFF(absPath)
	if err != nil {
		fmt.Printf("Failed to load GeoTIFF: %v\n", err)
		return
	}
	fmt.Println("GeoTIFF loaded successfully")

	// Test with the provided high precision coordinates
	lat := 31.03021050140226
	lon := 103.55147461467699
	expected := 837.6951116196124

	x, y, err := geoTiff.LatLonToPixel(lat, lon)
	if err != nil {
		fmt.Printf("Failed to convert coordinates (%.14f, %.14f): %v\n", lat, lon, err)
		return
	}

	fmt.Printf("Input coordinates:\n")
	fmt.Printf("  Lat: %.14f\n", lat)
	fmt.Printf("  Lon: %.14f\n", lon)
	fmt.Printf("Pixel coordinates:\n")
	fmt.Printf("  X: %.14f\n", x)
	fmt.Printf("  Y: %.14f\n", y)

	// Manual bilinear interpolation calculation
	x0 := int(math.Floor(x))
	y0 := int(math.Floor(y))
	x1 := x0 + 1
	y1 := y0 + 1

	fmt.Printf("\nSurrounding pixel coordinates:\n")
	fmt.Printf("  x0: %d, y0: %d\n", x0, y0)
	fmt.Printf("  x1: %d, y1: %d\n", x1, y1)

	// Get the values at the four corners
	q00, _ := geoTiff.GetElevation(float64(x0), float64(y0))
	q01, _ := geoTiff.GetElevation(float64(x0), float64(y1))
	q10, _ := geoTiff.GetElevation(float64(x1), float64(y0))
	q11, _ := geoTiff.GetElevation(float64(x1), float64(y1))

	fmt.Printf("\nCorner pixel values:\n")
	fmt.Printf("  q00 (%d, %d): %.14f\n", x0, y0, q00)
	fmt.Printf("  q01 (%d, %d): %.14f\n", x0, y1, q01)
	fmt.Printf("  q10 (%d, %d): %.14f\n", x1, y0, q10)
	fmt.Printf("  q11 (%d, %d): %.14f\n", x1, y1, q11)

	// Calculate weights
	dx := x - math.Floor(x)
	dy := y - math.Floor(y)

	fmt.Printf("\nInterpolation weights:\n")
	fmt.Printf("  dx: %.14f\n", dx)
	fmt.Printf("  dy: %.14f\n", dy)

	// Manual bilinear interpolation
	f1 := (1 - dx) * (1 - dy) * q00
	f2 := dx * (1 - dy) * q10
	f3 := (1 - dx) * dy * q01
	f4 := dx * dy * q11
	result := f1 + f2 + f3 + f4

	fmt.Printf("\nManual bilinear interpolation steps:\n")
	fmt.Printf("  f1 = (1-dx)*(1-dy)*q00 = %.14f\n", f1)
	fmt.Printf("  f2 = dx*(1-dy)*q10 = %.14f\n", f2)
	fmt.Printf("  f3 = (1-dx)*dy*q01 = %.14f\n", f3)
	fmt.Printf("  f4 = dx*dy*q11 = %.14f\n", f4)
	fmt.Printf("  result = f1 + f2 + f3 + f4 = %.14f\n", result)

	// Compare with library function
	elevationVal, err := geoTiff.GetElevation(x, y)
	if err != nil {
		fmt.Printf("Failed to get elevation: %v\n", err)
		return
	}

	fmt.Printf("\nComparison:\n")
	fmt.Printf("  Manual calculation: %.14f\n", result)
	fmt.Printf("  Library function: %.14f\n", elevationVal)
	fmt.Printf("  Expected: %.14f\n", expected)
	fmt.Printf("  Manual difference: %.14f\n", result-expected)
	fmt.Printf("  Library difference: %.14f\n", elevationVal-expected)
}
